package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final Long expire = 1000 * 60 * 60l;
    private static final SecretKey secretKey = Keys.hmacShaKeyFor("b8ad08a3a547e35829b821b75370301dd8c4b06bdd7771f9b541a75914068718".getBytes());
    public static String creatToken(String username,Long userId){
        String token = Jwts.builder()
                .setSubject("login-token")
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .claim("userName", username)
                .claim("userId", userId)
                .signWith(secretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    public static Claims parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(secretKey).
                    build().parseClaimsJws(token);
            return claimsJws.getBody();

        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}



